import 'dart:convert';
import 'package:flutter/services.dart';

extension CustomStringNullExtension on String? {
  /// Returns `true` if the String is either null or empty.
  bool get isNullOrEmpty {
    if (this == null) {
      return true;
    }
    return this!.isEmpty;
  }

  bool get isNotNullAndNotEmpty => !isNullOrEmpty;

  /// Returns `true` if the String is either null or blank.
  bool get isNullOrBlank {
    if (this == null) {
      return true;
    }
    return this!.isBlankString;
  }

  bool get isNotNullAndNotBlank => !isNullOrBlank;
}

extension CustomStringExtension on String {
  bool get isBlankString => trim().isEmpty;

  bool get isNotBlankString => !isBlankString;

  /// utf8 字节长度
  int get utf8Length => utf8.encode(this).length;

  /// 强制保留length位小数，会进行4舍5入，不够会补0，默认保留2位小数
  String formatStringAsFixed({int length = 2}) {
    return double.parse(this).toStringAsFixed(length);
  }

  /// 去除小数点后不必要的0，比如1.0=>1,1.540=>1.54
  String formatStringSubLastZero() {
    final regex = RegExp(r'([.]*0)(?!.*\d)');
    final replace = regex.stringMatch(this);
    if (replace == null) {
      return this;
    } else {
      return replaceAll(replace, '');
    }
  }

  /// 加载本地资源
  Future<Uint8List> loadAssetData() async {
    assert(isNotEmpty);
    final bytes = await rootBundle.load(this);
    return bytes.buffer.asUint8List();
  }

  // HEX
  Color? get hexToColor {
    final val = int.tryParse(substring(1));
    if (val == null) return null;
    return Color(val);
  }

  Color? get ahexToColor {
    final val = int.tryParse(substring(3));
    final alpha = int.tryParse(substring(1, 3));
    if (val == null || alpha == null) return null;
    return Color(val).withAlpha(alpha);
  }
}
